﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions ;

namespace SugarFineUI.Framework.Uitility
{
    public partial class StringHelper
    {
        /// <summary>
        /// html相关字符串操作
        /// </summary>
        public class HTML
        {
            /// <summary>
            /// 过滤js脚本
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static string FilterJS(string str)
            {
                //https://www.xuebuyuan.com/1654749.html
                Regex re = new Regex("&#36;", RegexOptions.IgnoreCase);
                str = re.Replace(str, "$");
                re = new Regex("&#36", RegexOptions.IgnoreCase);
                str = re.Replace(str, "$");
                re = new Regex("&#39;", RegexOptions.IgnoreCase);
                str = re.Replace(str, "'");
                re = new Regex("&#39", RegexOptions.IgnoreCase);
                str = re.Replace(str, "'");

                string jslist = @"(&#([0-9][0-9]*)|function|meta|window.|script|js:|about:|file:|Document.|vbs:|frame|cookie|on(finish|mouse|Exit=|error|click|key|load|focus|Blur))";
                re = new Regex("<((.[^>]*" + jslist + "[^>]*)|" + jslist + ")>", RegexOptions.IgnoreCase);
                str = re.Replace(str, "&lt;$1&gt;");

                return str;
            }

            ///<summary> 
            ///TextBox文本转成html字符实体 
            ///</summary> 
            ///<param  name="text">TextBox文本</param> 
            ///<returns></returns> 
            public static string TextBoxToHtml(string text)
            {
                StringBuilder sb = new StringBuilder(text);
                sb.Replace("&", "&amp");
                sb.Replace("\"", "&quot;");
                sb.Replace(" ", "&nbsp;");
                sb.Replace("<", "&lt;");
                sb.Replace(">", "&gt;");
                sb.Replace("\n", "<br/>");
                return sb.ToString();
            }

            /// <summary>
            /// html字符实体还原
            /// </summary>
            /// <param name="html"></param>
            /// <returns></returns>
            public static string HtmlToTextBox(string html)
            {
                StringBuilder sb = new StringBuilder(html);
                sb.Replace("<br/>", "\n");
                sb.Replace("&gt;", ">");
                sb.Replace("&lt;", "<");
                sb.Replace("&nbsp;", " ");
                sb.Replace("&quot;", "\"");
                sb.Replace("&amp", "&");
                return sb.ToString();
            }
        }
    }
}
